<?php
/**
 * 用文件记录Context
 */
declare(strict_types=1);

namespace Libraries\ContextDrivers;

use Libraries\File;

class ContextInFile
{
    private static function getFile(string $strId, string $strKey): string
    {
        return CACHES_PATH . '/context/' . md5($strId . '|' . $strKey) . '.php';
    }

    public static function get(string $strId, string $strKey)
    {
        $strFile = self::getFile($strId, $strKey);
        return (file_exists($strFile) && is_file($strFile)) ? include(self::getFile($strId, $strKey)) : null;
    }

    public static function getMulti(array $arrIdKey): array
    {
        $arrRe = [];
        foreach ($arrIdKey as $strId => $arrKey) {
            foreach ($arrKey as $strKey) {
                $arrRe[$strId][$strKey] = self::get($strId, $strKey);
            }
        }
        return $arrRe;
    }

    public static function set(string $strId, string $strKey, $mixVal): bool
    {
        return File::writePhpData(self::getFile($strId, $strKey), $mixVal, true);
    }

    public static function setMulti($arrIdKeyData): bool
    {
        if (!$arrIdKeyData) {
            return false;
        }
        $blnRe = true;
        foreach ($arrIdKeyData as $strId => $arrKeyData) {
            foreach ($arrKeyData as $strKey => $mixVal) {
                if (!$blnRe) {
                    break;
                }
                $blnRe = self::set($strId, $strKey, $mixVal);
            }
        }
        return $blnRe;
    }

    public static function del(string $strId, string $strKey): bool
    {
        return File::del(self::getFile($strId, $strKey));
    }

    public static function delMulti(array $arrIdKey): bool
    {
        if (!$arrIdKey) {
            return false;
        }
        foreach ($arrIdKey as $strId => $arrKey) {
            foreach ($arrKey as $strKey) {
                self::del($strId, $strKey);
            }
        }
        return true;
    }
}
